﻿using System;
using System.Web;
using System.Web.Security;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using INHollandair.Core.Models;
using INHollandair.Core.Services;

namespace INHollandair.Account
{
    public partial class Settings : System.Web.UI.Page
    {
        private readonly UserService _svc = new UserService();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                //Load data for labels
                LoadData();

                //Load order history
                LoadOrderHistory();
            }
            else
            {
                Response.Redirect("~/Account/Login.aspx?ReturnUrl=%2fAccount%2fSettings.aspx");
            }
        }

        protected void LoadData()
        {
            //Get data from database
            User user = _svc.GetUserByName(HttpContext.Current.User.Identity.Name);

            //Set labels
            username_lbl.Text = user.Name;
            email_lbl.Text = user.Email;
            points_lbl.Text = user.Points.ToString();
            dateregister_lbl.Text = user.DateRegistered.ToShortDateString();
        }

        protected void LoadOrderHistory()
        {
            //Get user from database
            User user = _svc.GetUserByName(HttpContext.Current.User.Identity.Name);

            //Setup order service
            OrderService orderService = new OrderService();

            //Get data from database
            List<OrderHistory> orderHistory = orderService.GetOrdersByUserId(user.Id);
            OrderedProducts.DataSource = orderHistory;
            OrderedProducts.DataBind();
        }

        protected void ProductGrid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "CancelOrder")
            {
                Response.Redirect("~/Shop/CancelOrder.aspx?OrderUrl=" + e.CommandArgument);
            }
        }

        protected void edituser_Click(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                Response.Redirect("~/Account/ChangeUser.aspx");
            }
        }

        protected void deleteaccount_Click(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                //Get data from database
                User user = _svc.GetUserByName(HttpContext.Current.User.Identity.Name);
                user.IsDeleted = true;

                //Remove user
                _svc.UpdateUser(user);

                Session.Abandon();
                FormsAuthentication.SignOut();

                Response.Redirect(Request.Url.AbsoluteUri);
            }
        }
    }
}